package com.vcredit.creditcat.manager.eduquery;

import com.alibaba.dubbo.config.annotation.Service;
import com.vcredit.bird.service.eduquery.EduQueryService;
import com.vcredit.bird.vo.eduquery.ChsiEduinfo;
import com.vcredit.bird.vo.eduquery.ChsiRollinfo;
import com.vcredit.bird.vo.eduquery.EduInitResult;
import com.vcredit.bird.vo.eduquery.EduQueryParamBird;
import com.vcredit.bird.vo.eduquery.EduQueryResponse;
import com.vcredit.creditcat.api.IEduQueryManager;
import com.vcredit.creditcat.dto.eduquery.AuthSchoolDto;
import com.vcredit.creditcat.dto.eduquery.EduInitDto;
import com.vcredit.creditcat.dto.eduquery.EduQueryParam;
import com.vcredit.creditcat.enumtype.AuthEduStatusEnum;
import com.vcredit.creditcat.enumtype.AuthEducationEnum;
import com.vcredit.creditcat.enumtype.AuthItemEnum;
import com.vcredit.creditcat.exception.BasicInfoException;
import com.vcredit.creditcat.manager.CreditCatProcessManager;
import com.vcredit.creditcat.model.AuthItem;
import com.vcredit.creditcat.model.AuthLog;
import com.vcredit.creditcat.model.AuthPersonalInfo;
import com.vcredit.creditcat.model.AuthProccess;
import com.vcredit.creditcat.model.AuthSchoolInfo;
import com.vcredit.creditcat.model.Cust;
import com.vcredit.creditcat.service.AuthLogService;
import com.vcredit.creditcat.service.AuthPersonalInfoService;
import com.vcredit.creditcat.service.AuthProccessService;
import com.vcredit.creditcat.service.AuthSchoolInfoService;
import com.vcredit.creditcat.service.product.util.EnumExtUtil;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.BeanUtil;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service(protocol = {"protocol1"}, version = "1.0")
public class EduQueryManager implements IEduQueryManager {

  @Autowired
  private EduQueryService educationService;
  @Autowired
  private AuthSchoolInfoService authSchoolInfoService;
  @Autowired
  private AuthPersonalInfoService authPersonalInfoService;
  @Autowired
  private CreditCatProcessManager creditCatProcessManager;
  @Autowired
  private AuthProccessService authProccessService;
  @Autowired
  private AuthLogService authLogService;

  @Log
  @Override
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public EduInitDto init(Cust cust) throws Exception {
    //验证基本信息是否认证
//    AuthProccess authProcess = authProccessService.findByIdForUpdate(cust.getLastProccessId());
//    if ((authProcess.getSuccessCode() & AuthItemEnum.BASE_INFO.getCode()) != AuthItemEnum.BASE_INFO
//        .getCode()) {
//      throw new BasicInfoException("请先认证基本信息");
//    }
    //学信网初始化
    EduInitResult eduInitResult = educationService
        .eduQueryInit(EduQueryService.class.getSimpleName().toUpperCase());
    EduInitDto eduInitDto = new EduInitDto();
    BeanUtil.copy(eduInitResult, eduInitDto);
    return eduInitDto;
  }

  @Log
  @Override
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public AuthSchoolDto eduQuery(EduQueryParam eduparam, Cust currentCust) throws Exception {
    EduQueryParamBird param = new EduQueryParamBird(eduparam.getChsiToken(),
        eduparam.getAccountName(),
        eduparam.getAccountPwd(), eduparam.getSmsVCode(), eduparam.getIdentityCard(),
        eduparam.getMobileNo(), "XINYONGMAO");
    // 调用学信网接口取得学信信息
    EduQueryResponse eduQueryResult = educationService.eduQuery(param);
    AuthSchoolInfo authSchoolInfo = new AuthSchoolInfo();
    if (null == eduQueryResult) {
      AuthSchoolDto authSchoolDto = new AuthSchoolDto();
      authSchoolDto.setAuthStatus(AuthEduStatusEnum.NOT_CERTIFIED.getCode());
      return authSchoolDto;
    } else {
      if (!eduQueryResult.getIdentityCard().equals(currentCust.getCustIdno()) &&
          !eduQueryResult.getName().equals(currentCust.getCustName())) {
        throw new BasicInfoException("本人与学信网信息不一致，请核实");
      }
    }
    AuthSchoolInfo authInfo = authSchoolInfoService.findByProccessId(eduparam.getProccessId());
    BeanUtil.copy(eduQueryResult, authSchoolInfo);
    BeanUtil.copy(
        eduQueryResult.getChsiRollinfo().size() > 0 ? eduQueryResult.getChsiRollinfo().get(0)
            : new ChsiRollinfo(), authSchoolInfo);
    BeanUtil.copy(
        eduQueryResult.getChsiEduinfo().size() > 0 ? eduQueryResult.getChsiEduinfo().get(0)
            : new ChsiEduinfo(), authSchoolInfo);
    authSchoolInfo.setProccessId(eduparam.getProccessId());
    authSchoolInfo.setRace(null); //TODO:由于返回字符串超过表字段长度，先不保存民族
    if (null != authInfo) {
      authSchoolInfo.setAuthSchoolId(authInfo.getAuthSchoolId());
      authSchoolInfoService.update(authSchoolInfo);
    } else {
      authSchoolInfoService.insert(authSchoolInfo);
    }
    AuthPersonalInfo authPersonalInfo = new AuthPersonalInfo();
    authPersonalInfo.setProccessId(eduparam.getProccessId());
    List<AuthPersonalInfo> authPersonalInfoList = authPersonalInfoService.find(authPersonalInfo);
    AuthSchoolDto result = new AuthSchoolDto();
    String degree = eduQueryResult.getDegree();
    // 个人信息表不为空且个人学历不为空且个人学历与学信信息学历相等
    if (null != authPersonalInfoList && 0 < authPersonalInfoList.size()
        && null != authPersonalInfoList.get(0).getEducationKey()
        && StringUtils.isNotBlank(degree)) {
      Integer educationKey = authPersonalInfoList.get(0).getEducationKey();
      if (degree.contains("本科") || degree.contains("专升本") || degree.contains("学士")) {
        degree = "大学本科";
      } else if (degree.contains("博士") || degree.contains("硕士") || degree.contains("研究生")) {
        degree = "硕士及以上";
      } else if (degree.contains("专科")) {
        degree = "大专";
      }
      AuthEducationEnum educationEnum = EnumExtUtil
          .getEnumOnValue(AuthEducationEnum.class, degree, "desc");
      if (educationEnum != null && educationEnum.getCode().equals(educationKey)) {
        result.setAuthStatus(AuthEduStatusEnum.CERTIFIED.getCode());
        // 客户实名认证操作
        AuthItem authItem = new AuthItem();
        authItem.setAuthCode(AuthItemEnum.EDUCATION.getCode());
        creditCatProcessManager.itemDone(authItem, eduparam.getProccessId());
        authLogService.insert(new AuthLog(eduparam.getProccessId(), currentCust.getCustId(),
            AuthItemEnum.EDUCATION.getCode(), "", new Date()));
      } else {
        result.setAuthStatus(AuthEduStatusEnum.AUTH_REJECT.getCode());
      }
    } else {
      result.setAuthStatus(AuthEduStatusEnum.NOT_CERTIFIED.getCode());
    }
    // 更新学籍信息认证状态
    AuthSchoolInfo updateSchoolInfoState = new AuthSchoolInfo();
    updateSchoolInfoState.setAuthSchoolId(authSchoolInfo.getAuthSchoolId());
    updateSchoolInfoState.setAuthState(result.getAuthStatus());
    authSchoolInfoService.update(updateSchoolInfoState);
    return result;
  }
}
